// Copyright Epic Games, Inc. All Rights Reserved.
#include <upstream/upstreamservice.h>

#include <upstream/upstreamcache.h>
#include <zenhttp/auth/authmgr.h>

#include <zencore/compactbinarybuilder.h>
#include <zencore/string.h>

namespace zen {

using namespace std::literals;

HttpUpstreamService::HttpUpstreamService(UpstreamCache& Upstream, AuthMgr& Mgr) : m_Upstream(Upstream), m_AuthMgr(Mgr)
{
	m_Router.RegisterRoute(
		"endpoints",
		[this](HttpRouterRequest& Req) {
			CbObjectWriter Writer;
			Writer.BeginArray("Endpoints"sv);
			m_Upstream.IterateEndpoints([&Writer](UpstreamEndpoint& Ep) {
				UpstreamEndpointInfo   Info	  = Ep.GetEndpointInfo();
				UpstreamEndpointStatus Status = Ep.GetStatus();

				Writer.BeginObject();
				Writer << "Name"sv << Info.Name;
				Writer << "Url"sv << Info.Url;
				Writer << "State"sv << ToString(Status.State);
				Writer << "Reason"sv << Status.Reason;
				Writer.EndObject();

				return true;
			});
			Writer.EndArray();
			Req.ServerRequest().WriteResponse(HttpResponseCode::OK, Writer.Save());
		},
		HttpVerb::kGet);
}

HttpUpstreamService::~HttpUpstreamService()
{
}

const char*
HttpUpstreamService::BaseUri() const
{
	return "/upstream/";
}

void
HttpUpstreamService::HandleRequest(zen::HttpServerRequest& Request)
{
	m_Router.HandleRequest(Request);
}

}  // namespace zen
